package com.cx.model.pinghe;

import com.cx.entity.PhStudent;
import com.cx.entity.RestResp;
import com.cx.service.PhStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

/**
 * @program: pms
 * @author: cx
 * @description: 平和学生人脸控制层
 * @create: 2025-02-08 10:59
 **/
@RestController
@RequestMapping("/ph")
public class StudentController {
    @Resource
    private PhStudentService phStudentService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * @return RestResp
     * @Descreption 搜索回显学生数据
     * @author cx
     * @date 2025-02-10
     */
    @PostMapping("/studentList")
    public RestResp addCustomer(@RequestBody PhStudent phStudent) {
        List<PhStudent> list = phStudentService.getList(phStudent);
        int count = phStudentService.count(phStudent);
//        list = list.subList(0, Math.min(list.size(), 30));
        return RestResp.success(count, list);

    }

    @GetMapping("/download/{id}")
    public void download(@PathVariable Integer id, HttpServletResponse response) {

        String imagePath = redisTemplate.opsForValue().get("Ph:studentId" + id);

        if(imagePath==null){
            // 根据id获取图片路径，这里假设图片路径存储在某个服务中
            PhStudent phStudent = phStudentService.selectByPrimaryKey(id);
             imagePath = phStudent.getImgUrl();
            if (imagePath == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            redisTemplate.opsForValue().set("Ph:studentId"+id,imagePath);
        }
        // 输入流 读取 ，输出流 写回浏览器
        try {
            // 输入流 读取文件内容
            FileInputStream inputStream = new FileInputStream(new File(imagePath));
            // 输出流,通过输出流将文件回写到浏览器，在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();
            // 表示图片文件
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            // 文件读取：返回值为int,当返回会值为-1表示已经读完了
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                // 刷新
                outputStream.flush();
            }
            // 关闭资源
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    public static void main(String[] args) {
        String str = "初中部,九年级7班学生,九年级,初中住校,学生,";
        if (str.endsWith(",")) {
            str = str.substring(0, str.length() - 1);

        }
        System.out.println(str);

    }
}


